using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.RoutingSteps.Commands;

/// <summary>
/// 工艺路线步骤创建命令。
/// </summary>
public sealed record CreateRoutingStepCommand(ProcRoutingStepDto Routing) : IRequest<IResult<bool>>;

internal sealed class CreateRoutingStepCommandHandler(IRepository<ProcRoutingStep> repo) : IRequestHandler<CreateRoutingStepCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateRoutingStepCommand request, CancellationToken cancellationToken)
    {
        var step = request.Routing.Adapt<ProcRoutingStep>();
        // 排序 & 前一步骤的前置步骤
        var prevStep = await repo.FirstOrDefaultAsync(m => m.RoutingId == step.RoutingId, m => m.Seq, true, cancellationToken);
        if (prevStep != null)
        {
            step.Seq = prevStep.Seq + 1; // 序号累加
            step.PrevStepId = prevStep.Id; // 当前步骤的前置步骤为前一步骤
        }
        else
        {
            step.Seq = 1;
        }
       
        var id = await repo.InsertReturnSnowflakeIdAsync(step, cancellationToken);

        // 更新前一步骤
        if (prevStep != null)
        {
            prevStep.NextStepId = id; // 前一步骤的后置步骤为当前步骤
            await repo.UpdateAsync(prevStep, m => new
            {
                m.NextStepId,
                m.UpdatedBy,
                m.UpdatedTime,
            }, cancellationToken);
        }

        return Result.From(true);
    }
}
